<?php

namespace frontend\modules\shop\controllers;

use common\components\Helper;
use common\components\Upload;
use common\models\articlesite\ArticlesiteArticle;
use common\models\business\BusinessContract;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessInspection;
use common\models\business\BusinessPig;
use common\models\business\BusinessPigFile;
use common\models\business\BusinessUser;
use common\models\business\BusinessVariety;
use common\models\business\NewBusinessInspection;
use common\models\shop\ShopSlide;
use common\models\sys\SysSetting;
use frontend\controllers\BaseMobileController;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\helpers\Url;
use yii\web\Response;


/**
 * Class PersonController
 * @package frontend\modules\business\controllers
 * 领养相关控制器
 */
class RasingController extends BaseMobileController
{



    public function actionPreIndex()
    {
        if(isset($_SESSION['agree']) && $_SESSION['agree']){
            header("location:".Url::to('index'));
            exit;
        }
        if(\Yii::$app->request->isPost){
            $_SESSION['agree'] = true;
            return json_encode(['status'=>0]);
        }

        $xieyi = (new Query())->select("*")->from(ArticlesiteArticle::tableName())
            ->where('usefor=:usefor',[':usefor'=>ArticlesiteArticle::USEFOR_XIEYI])
            ->one();

        return $this->render('@template/mobile/renyangxieyi.html',[
            'xieyi' => $xieyi,
        ]);
    }

    /**
     * @return string
     * 领养首页
     */
    public function actionIndex()
    {
        $slids = ShopSlide::find()->select('picture')->where('status=:status and type=:type',[':status'=>ShopSlide::ACTIVE_STATUS,':type'=>ShopSlide::TYPE_RASING])->asArray()->all();
        $banner = [];
        foreach ($slids as $slid => $row) {
            $banner[] = Upload::checkGetUrl($row['picture']);
        }

        //取出所有的品种
        $variety = BusinessVariety::find()
            ->select('picture as img,id,title as name,isindex')
            ->where('canlivery=:can',[':can'=>BusinessPig::CANLIVERY])
            ->asArray()
            ->all();
        $command = [];
        $i = 0;
        foreach ($variety as $key => $row)
        {
            if($row['isindex'] == BusinessVariety::INDEX){
                $command[$i] = $row;
                $command[$i]['img'] = Upload::checkGetUrl($row['img']);
                $command[$i]['url'] = Url::to(['/shop/rasing/list','vid'=>$row['id']]);
                $i++;
            }
            $variety[$key]['url'] = Url::to(['/shop/rasing/list','vid'=>$row['id']]);
        }


        //取出所有的可以养仔猪
        $query = (new Query())->select('p.no,p.id,planout,p.batch as title,photo as img,p.price,fileid,p.unino,v.title as varname,p.lingperson')
            ->from(BusinessPig::tableName().' as p')
            ->leftJoin(BusinessPigFile::tableName().' as pf','p.fileid=pf.id')
            ->leftJoin(BusinessVariety::tableName().' as v','v.id=p.varietyid')
            ->limit(10)
            ->orderBy(["CONVERT(REPLACE (p.no, '-',''),SIGNED)"=>SORT_ASC]);

        if(!\Yii::$app->request->get('vid')){      //
            $pigs = $query->where('p.canlivery=:can',[':can'=>BusinessPig::CANLIVERY])
                ->all();
        }else{
            $pigs = $query->where('p.canlivery=:can and p.varietyid=:vid',[':can'=>BusinessPig::CANLIVERY,':vid'=>\Yii::$app->request->get('vid')])
                ->all();
        }

        foreach ($pigs as $key => $row)
        {
            $pigs[$key]['price'] = floatval($row['price']);
            $pigs[$key]['img'] = Upload::checkGetUrl($row['img']);
            $pigs[$key]['planout'] = date('Y-m-d',$row['planout']);
            $pigs[$key]['url'] = Url::to(['/shop/rasing/detail','id'=>$row['id']]);
        }

        return $this->render('@template/mobile/raising.html',[
            'pigs' => \GuzzleHttp\json_encode($pigs),
            'variety' => \GuzzleHttp\json_encode($variety),
            'banner' => \GuzzleHttp\json_encode($banner),
            'command' => \GuzzleHttp\json_encode($command)
        ]);
    }


    /**
     * @return array
     * 领养仔猪加载更多
     */
    public function actionLoadMore()
    {
        $pindex = \Yii::$app->request->post('pindex');
        $pindex = $pindex?$pindex:1;
        $pagesize = 10;
        $vid = \Yii::$app->request->post('vid');

        //取出所有的可以养仔猪
        $query = (new Query())->select('p.no,p.id,planout,p.batch as title,photo as img,p.price,fileid,p.unino,v.title as varname,p.lingperson')
            ->from(BusinessPig::tableName().' as p')
            ->leftJoin(BusinessPigFile::tableName().' as pf','p.fileid=pf.id')
            ->leftJoin(BusinessVariety::tableName().' as v','v.id=p.varietyid')
            ->limit($pagesize)
            ->orderBy(["CONVERT(REPLACE (p.no, '-',''),SIGNED)"=>SORT_ASC])
            ->offset(($pindex-1)*$pagesize);

        if(!$vid){      //
            $pigs = $query->where('p.canlivery=:can',[':can'=>BusinessPig::CANLIVERY])
                ->all();
        }else{
            $pigs = $query->where('p.canlivery=:can and p.varietyid=:vid',[':can'=>BusinessPig::CANLIVERY,':vid'=>$vid])
                ->all();
        }

        foreach ($pigs as $key => $row)
        {
            $pigs[$key]['price'] = floatval($row['price']);
            $pigs[$key]['img'] = Upload::checkGetUrl($row['img']);
            $pigs[$key]['planout'] = date('Y-m-d',$row['planout']);
            $pigs[$key]['url'] = Url::to(['/shop/rasing/detail','id'=>$row['id']]);
        }

        \Yii::$app->response->format = Response::FORMAT_JSON;
        return $pigs;

    }


    /**
     * @return string
     * 领养仔猪的列表
     */
    public function actionList()
    {

        //取出所有的品种
        $variety = BusinessVariety::find()
            ->select('picture as img,id,title as name')
            ->where('canlivery=:can',[':can'=>BusinessPig::CANLIVERY])
            ->asArray()
            ->all();
        foreach ($variety as $key => $row)
        {
            $variety[$key]['img'] = Upload::checkGetUrl($row['img']);
            $variety[$key]['url'] = Url::to(['/shop/rasing/list','vid'=>$row['id']]);
        }


        //取出所有的可以养仔猪
        $pigs = (new Query())->select('p.id,p.no,planout,pf.name as title,photo as img,p.price,fileid,p.unino,v.title as varname,p.lingperson')
            ->from(BusinessPig::tableName().' as p')
            ->leftJoin(BusinessPigFile::tableName().' as pf','p.fileid=pf.id')
            ->leftJoin(BusinessVariety::tableName().' as v','v.id=p.varietyid')
            ->limit(10)
            ->orderBy(["CONVERT(REPLACE (p.no, '-',''),SIGNED)"=>SORT_ASC])
            ->where('p.canlivery=:can and p.varietyid=:vid',[':can'=>BusinessPig::CANLIVERY,':vid'=>\Yii::$app->request->get('vid')])
            ->all();



        foreach ($pigs as $key => $row)
        {
            $pigs[$key]['price'] = floatval($row['price']);
            $pigs[$key]['img'] = Upload::checkGetUrl($row['img']);
            $pigs[$key]['planout'] = date('Y-m-d',$row['planout']);
            $pigs[$key]['url'] = Url::to(['/shop/rasing/detail','id'=>$row['id']]);
        }

        return $this->render('@template/mobile/raising_list.html',[
            'pigs' => \GuzzleHttp\json_encode($pigs),
            'variety' => \GuzzleHttp\json_encode($variety),
            'vid' => \Yii::$app->request->get('vid')
        ]);

    }






    /**
     * @return string
     * 认养仔猪详情
     */
    public function actionDetail($id)
    {

        $pig = BusinessPig::find()
            ->alias('p')
            ->select('p.id,p.no,p.photo,p.price,p.intime,p.livery,p.planout,p.video,v.title as vname,p.batch,v.descripation as info,pf.father as f_no,pf.mathor as m_no,pf.matherphoto as m_img,pf.fatherphoto as f_img,pf.constract_id,p.lingperson')
            ->leftJoin(BusinessVariety::tableName().' as v','p.varietyid=v.id')
            ->leftJoin(BusinessPigFile::tableName().' as pf','pf.id=p.fileid')
            ->where('p.id=:id',[':id'=>$id])
            ->asArray()
            ->one();
        if(empty($pig)){
            return $this->timealert('您访问的仔猪不存在',\Yii::$app->request->getReferrer());
        }
        //处理图片
        $banner = Upload::checkGetUrl($pig['photo'],true,'photo');
        $pig['f_img'] = Upload::checkGetUrl($pig['f_img'],false,'f_img');
        $pig['m_img'] = Upload::checkGetUrl($pig['m_img'],false,'m_img');
        //处理视频
        $pig['video'] = Upload::checkGetUrl($pig['video'],false,'video');
        //var detail = {title:"第28-2期黑山猪散养",period:"12个月",cost:5000,profit:900,ratio:0.45,leftnum:5,img:"/static/images/pig3.jpg",name:"牧心一号",info:'<p>位于柞水溶洞山下，周边环境优美，开门见山，空气清新。我们家有五间房子，房间设施整洁干净，有完整的卫浴设施。欢迎大家来我家游玩。详细介绍文字，后台可自定义编辑图文混排。</p><img src="/static/images/farmdetail.jpg" alt="">',contract_no:"",slaughterhouse:"",no:"",address:"",f_no:"",m_no:"",records:[{title:"于2017-06-02巡检",no:"1",who:"仔仔",url:""}]};
        $pig['title'] = $pig['vname'].':'.$pig['no'];

        //计算出栏
        $totaltime = intval($pig['planout'])-intval($pig['intime']);
        if($totaltime > 0){
            $pig['ratio'] = round((time()-$pig['intime'])/$totaltime,2)*100;
        }else{
            $pig['ratio'] = 100;
        }
        $pig['leftnum'] = Helper::dateDifference(date('Y-m-d',$pig['planout']),date('Y-m-d'));   //出栏需要日期
        $pig['img'] = Upload::checkGetUrl($pig['photo'],false,'photo');

        $pig['intime'] = date('Y-m-d',$pig['intime']);
        $pig['planout'] = date('Y-m-d',$pig['planout']);

        //获取合同编号
        $pig['contract_no'] = BusinessContract::find()->select('no')->where('id=:id',[':id'=>$pig['constract_id']])->asArray()->scalar();

        //取出农户
        $farmer = BusinessFarmers::find()->select('name as farmer,addressdetail')->where('id=:id',[':id'=>$pig['livery']])->asArray()->one();
        $pig['farmer'] = $farmer['farmer'];
        $pig['address'] = $farmer['addressdetail'];

        //获取巡检
//        $records = BusinessInspection::find()->select('createtime,id,business_person')->where('pigid=:pigid and status=:status and is_del=:is_del',[':pigid'=>$id,':status'=>BusinessInspection::STATUS_PASSED,':is_del'=>BusinessInspection::ISDEL_NODEL])->asArray()->all();
        $records = NewBusinessInspection::find()->select('createtime,id,business_person')->where('pigid=:pigid and status=:status and is_del=:is_del',[':pigid'=>$id,':status'=>BusinessInspection::STATUS_PASSED,':is_del'=>BusinessInspection::ISDEL_NODEL])->asArray()->all();

        if($records){
            foreach ($records as $key => &$row)
            {
                $row['title'] = date('Y-m-d',$row['createtime']);
                $row['who'] = $row['business_person'];
                $row['no'] = ($key+1);
                $row['url'] = Url::to(['/shop/site/new-from-detail','recordid'=>$row['id']]);
            }
        }
        $pig['records'] = $records;

        //取出认养协议
        $article = ArticlesiteArticle::find()->select('title,file')->where('usefor=:usefor',[':usefor'=>ArticlesiteArticle::USEFOR_XIEYI])->asArray()->one();

        $article['file'] = Upload::checkGetUrl($article['file']);

        //取出电话号码
        $tel = (new Query())->select('phone')->from(BusinessUser::tableName())->where('id=:id',[':id'=>$this->user['userid']])->scalar();
        $pig['tel']= $tel;
        $pig['slaughterhouse'] = '柞水';
        return $this->render('@template/mobile/raisingdetail.html',[
            'banner' => $banner,
            'pig' => \GuzzleHttp\json_encode($pig),
            'id' => $id,
            'article' => $article,
            'lingperson' => $pig['lingperson']
        ]);

    }


    /*
     * 填写订单页
     */
    public function actionRasingForm($id)
    {
        //取出认养协议
        $article = ArticlesiteArticle::find()->select('title,file')->where('usefor=:usefor',[':usefor'=>ArticlesiteArticle::USEFOR_XIEYI])->asArray()->one();

        if(empty($article)){
            $article['title'] = '用户协议';
            $article['file'] = '';
        }else{
            $article['file'] = Upload::checkGetUrl($article['file']);
        }

        $pig = BusinessPig::find()
            ->alias('p')
            ->select('p.ling_total_price,p.id,p.no,p.photo,p.price,p.intime,p.livery,v.title as vname,p.batch,v.descripation as info')
            ->leftJoin(BusinessVariety::tableName().' as v','p.varietyid=v.id')
            ->leftJoin(BusinessPigFile::tableName().' as pf','pf.id=p.fileid')
            ->where('p.id=:id',[':id'=>$id])
            ->asArray()
            ->one();
        if(empty($pig)){
            return $this->timealert('您访问的仔猪不存在',\Yii::$app->request->getReferrer());
        }

        //处理图片
        $pig['img'] = Upload::checkGetUrl($pig['photo'],false,'photo');
        $pig['farmer'] = BusinessFarmers::find()->select('name as farmer,addressdetail')->where('id=:id',[':id'=>$pig['livery']])->asArray()->scalar();
        $pig['title'] = $pig['vname'].':'.$pig['no'];

        $user = (new Query())->select('realname,phone')->from(BusinessUser::tableName())->where('id=:id',[':id'=>$this->user['userid']])->one();

        //取出认养协议
        $fileurl = Upload::checkGetUrl($article['file']);


        //取出增值服务描述
        $add_service = SysSetting::getValue('add_service');


        return $this->render('@template/mobile/rasing_form.html',[
            'article' => $article,
            'id' => $id,
            'pig' => $pig,
            'user' => $user,
            'fileurl' => $fileurl,
            'add_service' => $add_service
            ]);
    }


    /**
     * 搜索领养的仔猪
     */
    public function actionSearchPig()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $kwd = \Yii::$app->request->post('keywords');
        if(!$kwd)
        {
            return [];
        }
        //取出所有的可以养仔猪
        $query = (new Query())->select('p.no,p.id,planout,p.batch as title,photo as img,p.price,fileid,p.unino,v.title as varname,p.lingperson')
            ->from(BusinessPig::tableName().' as p')
            ->leftJoin(BusinessPigFile::tableName().' as pf','p.fileid=pf.id')
            ->leftJoin(BusinessVariety::tableName().' as v','v.id=p.varietyid');

        if(!\Yii::$app->request->get('vid')){      //
            $pigs = $query->where('p.canlivery=:can and lingperson=0 and p.`no` like :no',[':can'=>BusinessPig::CANLIVERY,':no' => "%$kwd%"])
                ->all();
        }else{
            $pigs = $query->where('p.canlivery=:can and lingperson=0 and p.varietyid=:vid and p.`no` like :no',[':can'=>BusinessPig::CANLIVERY,':vid'=>\Yii::$app->request->get('vid'),':no' => "%$kwd%"])
                ->all();
        }

        foreach ($pigs as $key => $row)
        {
            $pigs[$key]['price'] = floatval($row['price']);
            $pigs[$key]['img'] = Upload::checkGetUrl($row['img']);
            $pigs[$key]['planout'] = date('Y-m-d',$row['planout']);
            $pigs[$key]['url'] = Url::to(['/shop/rasing/detail','id'=>$row['id']]);
        }

        return $pigs;
    }



    //读取认养协议
    public function actionXieyi()
    {
        //取出认养协议
        $article = ArticlesiteArticle::find()->select('title,content')->where('usefor=:usefor',[':usefor'=>ArticlesiteArticle::USEFOR_XIEYI])->asArray()->one();

        return $this->render('@template/mobile/article_detail.html',[
            'detail' => $article
        ]);

    }


    public function actionDownLoad()
    {

        //防止导出乱码
        $file = '认养协议.doc';
//        iconv("UTF-8","ANSI",$file);
        iconv('utf-8', 'gb2312', $file);
        //取出认养协议
        $article = ArticlesiteArticle::find()->select('file')->where('usefor=:usefor',[':usefor'=>ArticlesiteArticle::USEFOR_XIEYI])->asArray()->one();
        $fileurl = Upload::checkGetUrl($article['file']);
        header('Location:'.$fileurl);
        exit;
//        return \Yii::$app->response->sendFile(Upload::checkGetPath($article['file']),$file,[
//            'mimeType' => 'application/octet-stream',
//        ]);
    }




}
